import cooApp, {
  ui,
  Widget,
  basicWidgets,
  coolink,
  cooInfo,
  Util,
} from 'coolink-ts'
import { Colors } from '../config'
import func, { px } from '../base/func'
import Center from '../widgets/Center'
import { showAutoHideToast } from '../widgets/Toast'


const {
  Page,
  AppBar,
  Container,
  Text,
  ScrollView,
  PdfView,
} = basicWidgets

export default class PDFPreviewPage extends Widget<any, any> {

  pdfRef: any;
  pdfRef_tv: any;

  state = {
    //当前页码
    currentPage:0,
    //总页码
    pageCount:0,
    curpage_total:"0/0",//0/0

    // 界面样式
    backgroundGradient: {
      colors: [0xFF9C04D0, 0xFFFF60D5],
      type: 'linear',
      begin: 'centerLeft',
      end: 'centerRight'
    },

    boxShadow: {
      color: Colors.Black,
      blurRadius: 24,
      spreadRadius: 0,
    },

  }

linkCommandProcess(msg: any, raw: any) {
  Util.log('linkCommandProcess: ' + JSON.stringify(msg));
  if (this.isTV()) {
      // 电视机处理逻辑
      if (msg?.cmd == 'setPage') {
        //跟随手机端切换页码
        this.pdfRef_tv.setPage((Number)(msg?.page))
      }
  } else {
      if (msg?.cmd == 'tv-ready') {
          showAutoHideToast("TV端已开启联动")
      }
      if (msg?.cmd == 'setPage') {
        //跟随电视端切换页码
        this.pdfRef.setPage((Number)(msg?.page))
      }
  }
}

widgetDidMount() {
  cooApp.pageDidShow();
  // 开启组件联动
  this.enableLinking('pdfPreviewPage-component');
  this.setLinkCommandCallback(this.linkCommandProcess.bind(this));

  if (this.isTv()) {
      this.sendLinkCommand({ cmd: 'tv-ready' });  // 如果是电视机，则发送“电视机已经启动准备好”的消息
  } else {
      
  }
}


isTV() {
  if (cooInfo.infos?.systemInfo?.os && (cooInfo.infos.systemInfo.os.indexOf('ccos') >= 0)) {
      return true;
  }
  return false;
}

pushToTv() {
  Util.log("wzh pushToTv");
  this.beforeLinkView();
}

beforeLinkView() {
  coolink.protocol.isConnected().then((res) => {
      if (res.code == 0 && res.connected) {
          // 判断手机端是否连接设备
          this.startTv();
      } else {
          func.getRemoteDeviceInfos(showAutoHideToast, '设备离线中，请检查设备是否断电断网');
      }
  }).catch((err) => {
      func.getRemoteDeviceInfos(showAutoHideToast, '设备离线中，请检查设备是否断电断网');
  });
}

startTv() {
  coolink.protocol.generateHttpP2PHostMapping(this.props.filePath).then((mapping) => {
    if(mapping.code == 0 && mapping.hostMapping) {
        let random1: string = (parseInt((Math.random() * 10000000).toString())).toString();
        let random2: string = (parseInt((Math.random() * 10000000).toString())).toString();
        let random3: string = (parseInt((Math.random() * 10000000).toString())).toString();
        let random4: string = (parseInt((Math.random() * 10000000).toString())).toString();
        coolink.protocol.sendMessage({
          "id": random1 + random2 + random3 + random4,
          "content": JSON.stringify({
                cmd: "start_tv_mini_app",
                content: JSON.stringify({
                    "cmd": "download",
                    "type": "doc",//doc、video、audio、image
                    "url":  mapping.hostMapping,
                    "file_name":this.props.fileName,
                    "content": JSON.stringify({
                      "mp_alias": "PDF阅读器",
                      "mp_bundle": "http://172.20.130.210:12345/bundle.js",
                      "mp_code": "coolink-mobile-applet/coo-pdf-reader",//未上架前，本地调试用miniApp_debug_example
                      "dev_name": "深圳市酷开软件技术有限公司",
                      "dev_type": "enterprise",
                      "mp_id": 33,
                      "mp_intro": "PDF大屏联动阅读器",
                      "mp_logo": "https://coolink.coocaa.com/app/favicon.png",
                      "mp_name": "PDF阅读器",
                      "mp_version": "1.0.0"
                  })
              }),
            }),
          "appTargetID": "coocaa-link-server",
          "appSourceID": "coolink-mobile-applet/coo-pdf-reader",//未上架前，本地调试用miniApp_debug_example
          "type": "TEXT",
          "extra": {},
          "reply": false,
          "broadcast": false
        } as any);
    } else {
      showAutoHideToast("error:"+mapping.msg)
    }
  }).catch((err)=>{
    showAutoHideToast(""+err.toString)
  })
}

onChangePdf = (res: any) => {
  switch(res.type){
    case "onPageChanged":
        //页码变化回调
        this.setState({
          pageCount:res.page_count,
          currentPage:res.current_page,
          curpage_total:((Number)(res.current_page)+1)+"/"+res.page_count
        })
        // showAutoHideToast("onPageChanged:"+res.value)
        let pageInex = (Number)(res.current_page)
        this.sendLinkCommand({ cmd: "setPage", page: pageInex })
        break
        default:
          showAutoHideToast("onChangePdf:"+res.type+"--"+res.value)
          break
  }
}

onChangePdf_tv = (res: any) => {
  switch(res.type){
    case "onPageChanged":
        //页码变化回调
        this.setState({
          pageCount:res.page_count,
          currentPage:res.current_page,
          curpage_total:((Number)(res.current_page)+1)+"/"+res.page_count
        })
        break
        default:
          showAutoHideToast("onChangePdf_tv:"+res.type+"--"+res.value)
          break
  }
}

dispatchKeyEvent_tv(obj) {
  switch(obj.keyCode) {
    case 19://上
    var pageInex = (Number)(this.state.currentPage )
    if(pageInex == 0){
        //已经是第一页了
        return
    }
    pageInex = pageInex-1
    this.pdfRef_tv.setPage((Number)(pageInex))
    this.sendLinkCommand({ cmd: "setPage", page: pageInex })
      break
    case 20://下
    pageInex = (Number)(this.state.currentPage )
    if(pageInex ==  (Number)(this.state.pageCount)-1){
      //已经是最后一页了
      return
    }
    pageInex = pageInex+1
    this.pdfRef_tv.setPage((Number)(pageInex))
    this.sendLinkCommand({ cmd: "setPage", page: pageInex })
      break
    case 21://左
      break
    case 22://右
      break
  }
}

getFilePath_tv():string{
  //从容器里面拿
  var miniAppExtParams = cooInfo.infos?.appInfo?.miniAppExtParams
  var filePath = ""
  if(miniAppExtParams) {
    filePath = JSON.parse(cooInfo.infos?.appInfo?.miniAppExtParams).filePath
  }
  return filePath
}

render() {
  const appbarHeight = ui.appbarHeight;
  const statusBarHeight = Math.round(ui.statusBarHeight);
  const bottomBarHeight = ui.bottomBarHeight;
  const clientHeight = ui.screenHeight - statusBarHeight - appbarHeight - bottomBarHeight;
  return (
      this.isTV() ?
      //tv端
      <Page>
        <Container relative={true} width={ui.screenWidth} height={ui.screenHeight} justifyContent={"center"} alignItems={'center'} dispatchKeyEvent={this.dispatchKeyEvent_tv.bind(this)} requestFocus={true}>
          <PdfView absolute={{ top: 0, left: 300 }} width={650} height={750} filePath={this.getFilePath_tv()} onChange={this.onChangePdf_tv.bind(this)} ref={(refElement)=>{this.pdfRef_tv = refElement;}}></PdfView>
          <Center absolute={{ top: 300, left: 350 }} height={px(40)} width={ui.screenWidth}>
            <Text richText={[{ text: this.state.curpage_total, color: 0xff000000 }]} margin={5} weight={'bolder'} color={Colors.Black} >{'当前页码: '}</Text>
          </Center>
        </Container>
      </Page>
      :
      //手机端
      <Page appBar={<AppBar title={this.props.fileName} backgroundColor={Colors.White} elevation />}>
        <Container relative={true} width={ui.screenWidth} height={clientHeight}>
          <Container relative={true} absolute={{ top: 0, left: (ui.screenWidth - px(320)) * 0.5 }} width={px(320)} >
            <PdfView  width={350} height={450} filePath={this.props.filePath} onChange={this.onChangePdf.bind(this)} ref={(refElement)=>{this.pdfRef = refElement;}}></PdfView>
          </Container>
          <Container relative={true} absolute={{ top: px(500), left: 0 }} height={px(210)} width={ui.screenWidth}>
              <Center absolute={{ top: 0, left: 0 }} height={px(40)} width={ui.screenWidth}>
                <Text richText={[{ text: this.state.curpage_total, color: 0xff000000 }]} margin={5} weight={'bolder'} color={Colors.Black} >{'当前页码: '}</Text>
              </Center>
              <Center absolute={{ top: 50, left: 0 }} height={px(60)} width={ui.screenWidth}>
                  <Container
                      width={px(270)}
                      height={px(56)}
                      borderRadius={px(25)}
                      justifyContent="center"
                      alignItems="center"
                      backgroundGradient={this.state.backgroundGradient as any}
                      boxShadow={this.state.boxShadow}
                      onTap={() => this.pushToTv()}
                  >
                      <Text text="电视联动" color={0xffffffff} size={px(20)}></Text>
                  </Container>
              </Center>
            </Container>
          </Container>
      </Page>
    )
  }
}


